package com.masterclient.app.modules.category;

import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.view.PagerAdapter;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.eoner.baselibrary.bean.firstpager.SearchConditionBean;
import com.eoner.baselibrary.bean.goods.ProductBean;
import com.eoner.baselibrary.utils.CloneUtil;
import com.eoner.baselibrary.utils.GlideUtil;
import com.eoner.baselibrary.utils.ScreenUtils;
import com.eoner.baselibrary.utils.ViewTransformUtil;
import com.masterclient.app.BaseActivity;
import com.masterclient.app.R;
import com.masterclient.app.modules.category.adapter.AttributesGridAdapter;
import com.masterclient.app.modules.category.adapter.CategoryGridAdapter;
import com.masterclient.app.modules.category.beans.CategoryDetailBean;
import com.masterclient.app.modules.category.contract.CategoryDetailContract;
import com.masterclient.app.modules.category.contract.CategoryDetailPresenter;
import com.masterclient.app.modules.goods.adapter.CommonGoodsRecyclerAdapter;
import com.masterclient.app.modules.search.SearchGoodBean;
import com.masterclient.app.modules.search.adapter.PromotionAdapter;
import com.masterclient.app.widget.GoodsItemDecoration;
import com.masterclient.app.widget.NonScrollGridView;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import jp.wasabeef.glide.transformations.RoundedCornersTransformation;

import static com.eoner.baselibrary.utils.ScreenUtils.dp2px;

/**
 * 作者：sean
 * 创建时间：2017/7/3 18:01
 * 功能说明：分类二级页面
 */

public class CategoryDetailActivity extends BaseActivity<CategoryDetailPresenter> implements CategoryDetailContract.View {


    @BindView(R.id.rl_back)
    RelativeLayout rlBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.rl_head)
    RelativeLayout rlHead;
    @BindView(R.id.tl_tabs)
    TabLayout tlTabs;
    @BindView(R.id.tv_all_brand)
    TextView tvAllBrand;
    @BindView(R.id.iv_arrow)
    ImageView ivArrow;
    @BindView(R.id.rl_arrow_right)
    RelativeLayout rlArrowRight;
    @BindView(R.id.rl_brands_selector)
    RelativeLayout rlBrandsSelector;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.tv_default)
    TextView tvDefault;
    @BindView(R.id.tv_sale_volume)
    TextView tvSaleVolume;
    @BindView(R.id.tv_price)
    TextView tvPrice;
    @BindView(R.id.tv_price_icon)
    ImageView tvPriceIcon;
    @BindView(R.id.tv_filt)
    TextView tvFilt;
    @BindView(R.id.tv_filt_layout)
    LinearLayout tvFiltLayout;
    @BindView(R.id.ll_selector)
    LinearLayout llSelector;
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout swipeLayout;
    @BindView(R.id.textView)
    TextView textView;
    @BindView(R.id.et_min_price)
    EditText etMinPrice;
    @BindView(R.id.et_max_price)
    EditText etMaxPrice;
    @BindView(R.id.ll_condition_other)
    LinearLayout llConditionOther;
    @BindView(R.id.tv_reset)
    TextView tvReset;
    @BindView(R.id.tv_complete)
    TextView tvComplete;
    @BindView(R.id.ll_bottom)
    LinearLayout llBottom;
    @BindView(R.id.left_drawer)
    RelativeLayout leftDrawer;
    @BindView(R.id.drawerLayout)
    DrawerLayout drawerLayout;
    @BindView(R.id.noScrollPromotion)
    NonScrollGridView noScrollPromotion;
    @BindView(R.id.ll_activity)
    LinearLayout llActivity;
    @BindView(R.id.iv_back_top)
    ImageView ivBackTop;
    @BindView(R.id.shadow)
    ImageView shadow;
    @BindView(R.id.category_brand_ll)
    LinearLayout categoryBrandLl;
    @BindView(R.id.brand_category_text)
    TextView brandCategoryText;
    @BindView(R.id.brand_category_nsgv)
    NonScrollGridView brandCategoryNsgv;
    @BindView(R.id.brand_category_arrow)
    ImageView brand_category_arrow;

    boolean isCategoryBrandAll=false;

    //    private CategoryFirstBean.DataBean category;
//    private CategoryBrandBean.DataBean brands;
    private int position = 0;
    private boolean changeBrand = true;
    private CommonGoodsRecyclerAdapter searchGoodRecyclerAdapter;
    private View headView;
    private ViewHolder holder;
    private SelectorPopWindow pop;
    private int[] ll_location = new int[2];
    private boolean popShowing;
    private AttributesGridAdapter categoryGridAdapter;

    private SearchConditionBean conditionBean;
    String keyword, sort = "new";
    private View footView;
    ImageView iv_bottom;

    private PromotionAdapter promotionAdapter;

    PagerAdapter pagerAdapter;

    List<SearchGoodBean.DataBean.ShAttributesBean> cloneAttrBeans;
    private List<ProductBean> goodList;
    private int total;
    private List<String>  category_brand_ids = new ArrayList<>();
    private List<CategoryDetailBean.ShItemsBean.ShCategorysBean> category_brands;
    private String cid = "",brandcategoryId = "",type="0";
    private boolean isFirst = true;
    private List<SearchGoodBean.DataBean.ShPromotionsBean> clonePromotions;

    private String from,image,title;
    //    private ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>();
    private View emptyView;
    private int status = 0;
    private List<CategoryDetailBean.ShTopArrBean> shBrands;



    private void clickView() {

        etMinPrice.setOnFocusChangeListener((v,hasFocus)-> {
            if(!hasFocus){
                hideSoftInput(etMinPrice);
            }
        });

        etMaxPrice.setOnFocusChangeListener((v,hasFocus)-> {
            if(!hasFocus){
                hideSoftInput(etMaxPrice);
            }
        });

        ivBackTop.setOnClickListener(v->{
            ivBackTop.setVisibility(View.GONE);
            recyclerView.scrollToPosition(0);
        });

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                int[] location = new int[2];
                holder.llSelector.getLocationOnScreen(location);

                if (location[1] <= ll_location[1]) {
                    llSelector.setVisibility(View.VISIBLE);
                } else {
                    llSelector.setVisibility(View.GONE);
                }

            }
        });

        llSelector.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                llSelector.getViewTreeObserver().removeOnPreDrawListener(this);
                llSelector.getLocationOnScreen(ll_location);
                return true;
            }
        });


        recyclerView.setOnTouchListener(
                new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        if (swipeLayout.isRefreshing()) {
                            return true;
                        } else {
                            return false;
                        }
                    }
                }
        );

        holder.tvFilt.setOnClickListener((tvFilt) -> {
            drawerLayout.openDrawer(Gravity.RIGHT);
        });

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);

                StaggeredGridLayoutManager manager = (StaggeredGridLayoutManager) recyclerView.getLayoutManager();
                int[] first = new int[manager.getSpanCount()];
                manager.findFirstCompletelyVisibleItemPositions(first);
                if (newState == RecyclerView.SCROLL_STATE_IDLE && (first[0] == 1 || first[1] == 1)) {
                    manager.invalidateSpanAssignments();
                }

                int[] firstVisibleItemPosition = new int[manager.getSpanCount()];
                manager.findFirstVisibleItemPositions(firstVisibleItemPosition);
                if(ivBackTop!=null) {
                    if (firstVisibleItemPosition[0] <= 7) {
                        ivBackTop.setVisibility(View.INVISIBLE);
                    } else {
                        ivBackTop.setVisibility(View.VISIBLE);
                    }
                }
//                LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager();
//                int firstVisibleItemPosition = manager.findFirstVisibleItemPosition();
//                // 当不滚动时
////                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
//                // 判断是否滚动超过一屏
//                if (firstVisibleItemPosition == 0) {
//                    ivBackTop.setVisibility(View.INVISIBLE);
//                } else {
//                    ivBackTop.setVisibility(View.VISIBLE);
//                }

//              } else if (newState == RecyclerView.SCROLL_STATE_DRAGGING) {//拖动中
//                    ivBackTop.setVisibility(View.INVISIBLE);
//              }
            }
        });


        searchGoodRecyclerAdapter.setOnLoadMoreListener(() -> {
            if (goodList.size() < total) {
                setSelectTag();
                changeBrand = false;
                getData(String.valueOf(goodList.size() / Integer.valueOf(PAGE_SIZE) + 1));
            }

        }, recyclerView);
        swipeLayout.setOnRefreshListener(() -> {
            status = 1;
            getGoodsFirstPage();
        });

    }

    @SuppressWarnings("ResourceType")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_category_detail);
        ButterKnife.bind(this);
        from = getBundleString("from");

//        ((LinearLayout.LayoutParams)textView.getLayoutParams()).setMargins(0, ImmersionBar.getStatusBarHeight(this),0,0);
        footView = View.inflate(mContext, R.layout.bottom_common, null);
        iv_bottom = (ImageView) footView.findViewById(R.id.iv_bottom);
        headView = View.inflate(mContext, R.layout.category_detail_head, null);
        holder = new ViewHolder(headView);
        holder.ivBanner.getLayoutParams().height = (int) ((ScreenUtils.getScreenWidth()-ScreenUtils.dp2px(32))*13/34f);
        conditionBean = new SearchConditionBean();

//        recyclerView.setLayoutManager(new GridLayoutManager(mContext, 2));

        StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
//        layoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_NONE);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setItemAnimator(null);
        recyclerView.addItemDecoration(new GoodsItemDecoration(dp2px(10)));
        searchGoodRecyclerAdapter = new CommonGoodsRecyclerAdapter();
        recyclerView.setAdapter(searchGoodRecyclerAdapter);
        searchGoodRecyclerAdapter.bindToRecyclerView(recyclerView);

        emptyView = View.inflate(mContext,R.layout.null_search,null);
        ((TextView)emptyView.findViewById(R.id.tv_tip)).setText("没有找到您要的商品");
        searchGoodRecyclerAdapter.setEmptyView(emptyView);
        emptyView.setVisibility(View.GONE);

        searchGoodRecyclerAdapter.addHeaderView(headView);
        searchGoodRecyclerAdapter.setHeaderAndEmpty(true);
        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ScreenUtils.dp2px(300));
        searchGoodRecyclerAdapter.getEmptyView().setLayoutParams(params);

        clickView();


        if("firstpage".equals(from)){//从首页跳转过来
            cid = getBundleString("cid");
            image = getBundleString("image");
            title = getBundleString("title");
            type = getIntent().getExtras().getString("type","0");
        }else {//从品类页跳转过来
            type = getIntent().getStringExtra("type");
            cid = getIntent().getStringExtra("cid");
            categoryBrandLl.setVisibility(View.VISIBLE);
            brandcategoryId = getIntent().getStringExtra("brand_category_id");
            image = getIntent().getStringExtra("image");
            title = getIntent().getStringExtra("title");
        }
        if ( "0".equals(type)){
            brandCategoryText.setText("店铺");
        }else {
            brandCategoryText.setText("分类");
        }

        if ("0".equals(type)||"1".equals(type)) {
            categoryGridAdapter = new AttributesGridAdapter(mContext);
        }
        changeBrand = true;
        leftDrawer.getLayoutParams().width = (int) (ScreenUtils.getScreenWidth() * 0.77);

        getData("1");
    }



    @Override
    protected void onResume() {
        MobclickAgent.onEvent(mContext, "page_category_detail");
        super.onResume();
    }

    /**
     * 切换品牌
     */
    private void getGoodsFirstPage() {
        ivBackTop.setVisibility(View.GONE);
        if (goodList != null) {
            goodList.clear();
            emptyView.setVisibility(View.GONE);
            searchGoodRecyclerAdapter.notifyDataSetChanged();
        }
        searchGoodRecyclerAdapter.setEnableLoadMore(true);
        conditionBean = new SearchConditionBean();
        resetAttr();

        if ("new".equals(sort)) {

        } else if ("hot".equals(sort)) {
            tvDefault.setTextColor(getResources().getColor(R.color.text_red));
            tvSaleVolume.setTextColor(0xFF222222);
            holder.tvDefault.setTextColor(getResources().getColor(R.color.text_red));
            holder.tvSaleVolume.setTextColor(0xFF222222);
            sort = "new";
        } else if ("price_desc".equals(sort) || "price_asc".equals(sort)) {
            tvDefault.setTextColor(getResources().getColor(R.color.text_red));
            tvSaleVolume.setTextColor(0xFF222222);
            holder.tvDefault.setTextColor(getResources().getColor(R.color.text_red));
            holder.tvSaleVolume.setTextColor(0xFF222222);
            tvPriceIcon.setImageResource(R.mipmap.paixu_icon);
            holder.tvPriceIcon.setImageResource(R.mipmap.paixu_icon);
//            Drawable nav_up = getResources().getDrawable(R.mipmap.paixu_icon);
//            nav_up.setBounds(0, 0, nav_up.getMinimumWidth(), nav_up.getMinimumHeight());
//            tvPrice.setCompoundDrawables(null, null, nav_up, null);
//            holder.tvPrice.setCompoundDrawables(null, null, nav_up, null);
            tvPrice.setTextColor(0xFF222222);
            holder.tvPrice.setTextColor(0xFF222222);
            sort = "new";
        }
        setSelectTag();

        changeBrand = true;
        getData("1");
        //        mPresenter.getBrandGoodList(true, null, conditionBean.getBrand_ids(), cids, null, conditionBean.getEnd_price(), keyword, String.valueOf(1), PAGE_SIZE, sort, null);

    }


    private void setSelectTag() {
        if(!TextUtils.isEmpty(conditionBean.getStart_price())||
                !TextUtils.isEmpty(conditionBean.getEnd_price())||
                (conditionBean.getAttributes()!=null && conditionBean.getAttributes().size() != 0)||
                !TextUtils.isEmpty(conditionBean.getPromotion_type())||
                (conditionBean.getCids()!=null&&conditionBean.getCids().size() != 0)){

//            tvFilt.setTextColor(getResources().getColor(R.color.text_red));
//            Drawable drawble_select=getResources().getDrawable(R.mipmap.shaixuan_select_icon);
//            drawble_select.setBounds(0, 0, drawble_select.getMinimumWidth(), drawble_select.getMinimumHeight());
//            tvFilt.setCompoundDrawables(null,null,drawble_select,null);

//            holder.tvFilt.setTextColor(getResources().getColor(R.color.text_red));
//            holder.tvFilt.setCompoundDrawables(null,null,drawble_select,null);

        }else {
//            tvFilt.setTextColor(0xFF222222);
//            Drawable drawble_select=getResources().getDrawable(R.mipmap.shaixuan_icon);
//            drawble_select.setBounds(0, 0, drawble_select.getMinimumWidth(), drawble_select.getMinimumHeight());
//            tvFilt.setCompoundDrawables(null,null,drawble_select,null);

//            holder.tvFilt.setTextColor(0xFF222222);
//            holder.tvFilt.setCompoundDrawables(null,null,drawble_select,null);
        }
    }


    private void initViews(CategoryDetailBean categoryDetailBean) {
        if(categoryDetailBean.getSh_items().getSh_products() == null||categoryDetailBean.getSh_items().getSh_products().size() == 0){
            searchError();
        }
        CategoryDetailBean.ShTopArrBean shBean = new CategoryDetailBean.ShTopArrBean();
        shBean.setSh_name("全部");
        shBean.setSh_id("");
        shBrands = categoryDetailBean.getSh_top_arr();
        shBrands.add(0, shBean);

        title = categoryDetailBean.getSh_title_name();
        tvTitle.setText(title);

        GlideUtil.displayImage(this,categoryDetailBean.getSh_brand_more_product(),iv_bottom);
//        App.picasso.load(categoryDetailBean.getSh_brand_more_product()).into(iv_bottom);
        for (int i = 0; i < shBrands.size(); i++) {
            LinearLayout rl = (LinearLayout) View.inflate(mContext, R.layout.item_brand_name, null);
            TextView tv_brand = (TextView) rl.findViewById(R.id.tv_brand);
            View indicator =  rl.findViewById(R.id.indicator);
            tv_brand.setText(shBrands.get(i).getSh_name());
            tlTabs.addTab(tlTabs.newTab().setCustomView(rl), false);
            tv_brand.setSelected(false);
            if (brandcategoryId.equals(shBrands.get(i).getSh_id())){
                position = i;
            }

            indicator.setSelected(false);
            shBrands.get(i).setSelect(false);
        }

        if (shBrands.size() <= 4) {
            rlArrowRight.setVisibility(View.GONE);
        } else {
            rlArrowRight.setVisibility(View.VISIBLE);
        }
        conditionType();

        pop = new SelectorPopWindow(mContext,categoryDetailBean.getSh_top_arr());
        rlArrowRight.setOnClickListener((view) -> {
            if (popShowing) {
                pop.dismiss();
                popShowing = false;
                tvAllBrand.setVisibility(View.GONE);
                shadow.setVisibility(View.VISIBLE);
                ivArrow.setImageResource(R.mipmap.search_down);
            } else {

//                if (Build.VERSION.SDK_INT < 24) {
//                    pop.showAsDropDown(rlBrandsSelector, 0, 0);
//                } else {
//                    // 适配 android 7.0
//                int[] location = new int[2];
//                rlBrandsSelector.getLocationOnScreen(location);
//                int x = location[0];
//                int y = location[1];
//                CommonUtil.showAsDropDown(pop,rlBrandsSelector,x,y);
                showAsDropDown(pop,rlBrandsSelector);
//                    pop.showAtLocation(rlBrandsSelector, Gravity.NO_GRAVITY, 0, y + rlBrandsSelector.getHeight());
//                }
//                pop.showAsDropDown(rlBrandsSelector);
                popShowing = true;
                tvAllBrand.setVisibility(View.VISIBLE);
                shadow.setVisibility(View.GONE);
                ivArrow.setImageResource(R.mipmap.search_up);
            }
        });
        pop.setOnItemClickListerner(new SelectorPopWindow.OnItemClickListerner() {
            @Override
            public void clickItem(int position) {
                tlTabs.getTabAt(position).select();
                brandcategoryId = shBrands.get(position).getSh_id();
            }

            @Override
            public void onDismiss() {
                popShowing = false;
                tvAllBrand.setVisibility(View.GONE);
                ivArrow.setImageResource(R.mipmap.search_down);
            }
        });

        tlTabs.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                tab.getCustomView().findViewById(R.id.tv_brand).setSelected(true);
                brandcategoryId = shBrands.get(tab.getPosition()).getSh_id();
                pop.changeSelect(tab.getPosition());
//                tvAllBrand.setText(shBrands.get(tab.getPosition()).getSh_name());
//                Log.e(TAG, "onTabSelected: "+status +"=="+ shBrands.get(tab.getPosition()).getSh_name());
                status = 1;
                resetAttr();
                getGoodsFirstPage();

            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                tab.getCustomView().findViewById(R.id.tv_brand).setSelected(false);
                tab.getCustomView().findViewById(R.id.indicator).setSelected(false);
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });

        if (isFirst) {
            tlTabs.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if("firstpage".equals(from)){
                        tlTabs.getTabAt(0).select();
                        tlTabs.getTabAt(0).getCustomView().findViewById(R.id.indicator).setSelected(true);
                    }else {
                        tlTabs.getTabAt(position).select();
                        tlTabs.getTabAt(position).getCustomView().findViewById(R.id.indicator).setSelected(true);
                    }
                }
            }, 200);
            isFirst = false;
        }

    }


    @Override
    protected void onStart() {

        super.onStart();
    }

    public void showAsDropDown(PopupWindow pw, View anchor) {

        if (Build.VERSION.SDK_INT >= 24) {

            Rect visibleFrame = new Rect();
            anchor.getGlobalVisibleRect(visibleFrame);
            int height = anchor.getResources().getDisplayMetrics().heightPixels - visibleFrame.bottom;
            pw.setHeight(height);
        }
            pw.showAsDropDown(anchor);
    }

    private void checkBrand(@IdRes int checkedId) {

    }

    @Override
    public void showSearchGood(CategoryDetailBean dataBean, boolean changeBrand) {

        if (swipeLayout.isRefreshing()) {
            swipeLayout.setRefreshing(false);
        }
//        Log.e("====","showSearchGood: status" + status );
        switch (status){
            case 0:
                initViews(dataBean);
                break;
        }
        if (categoryGridAdapter != null){
            brandCategoryNsgv.setAdapter(categoryGridAdapter);
            if (changeBrand) {
                if ("0".equals(type)) {
                    category_brands = (List<CategoryDetailBean.ShItemsBean.ShCategorysBean>) CloneUtil.deepClone(dataBean.getSh_items().getSh_brands());
                } else {
                    category_brands = (List<CategoryDetailBean.ShItemsBean.ShCategorysBean>) CloneUtil.deepClone(dataBean.getSh_items().getSh_categorys());
                }
            }
//            Log.e(TAG, "initViews: "+category_brands.size() );
            if (category_brands.size() == 0){
                categoryBrandLl.setVisibility(View.GONE);
            }else {
                categoryBrandLl.setVisibility(View.VISIBLE);
                categoryGridAdapter.setList(category_brands);
                if (category_brands.size()>3){
                    brand_category_arrow.setVisibility(View.VISIBLE);
                    categoryGridAdapter.setSize(false);
                }else {
                    brand_category_arrow.setVisibility(View.GONE);
                }

                brand_category_arrow.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (isCategoryBrandAll){
                            isCategoryBrandAll = false;
                            categoryGridAdapter.setSize(false);
                            brand_category_arrow.setImageResource(R.mipmap.search_down);
                        }else {
                            isCategoryBrandAll = true;
                            categoryGridAdapter.setSize(true);
                            brand_category_arrow.setImageResource(R.mipmap.search_up);
                        }
                    }
                });
            }
            brandCategoryNsgv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    CategoryDetailBean.ShItemsBean.ShCategorysBean shOptionsBean = category_brands.get(position);
                    if (shOptionsBean.isCheck()) {
                        shOptionsBean.setCheck(false);
                    } else {
                        shOptionsBean.setCheck(true);
                    }
                    categoryGridAdapter.notifyDataSetChanged();
                }
            });
        }else {
            categoryBrandLl.setVisibility(View.GONE);
        }


        if (changeBrand){
            ViewTransformUtil.glideImageView(this,dataBean.getSh_banner(),holder.ivBanner,
                    new RoundedCornersTransformation(ScreenUtils.dp2px(7), 0),R.mipmap.defaults_1);
        }
        if (dataBean.getSh_items().getSh_products() != null) {
            if ("1".equals(dataBean.getSh_items().getSh_page())&&dataBean.getSh_items().getSh_products().size() == 0){
                if (goodList == null) {
                    goodList = new ArrayList<>();
                }
                searchError();
            }else {
                if (goodList == null) {
                    goodList = new ArrayList<>();
                }
                goodList.addAll(dataBean.getSh_items().getSh_products());
            }
        }


        total = Integer.valueOf(dataBean.getSh_items().getSh_total());
        if(goodList!=null&&goodList.size()>0){
            emptyView.setVisibility(View.VISIBLE);
        }

        if ( goodList.size()<=20){
            searchGoodRecyclerAdapter.setNewData(goodList);
            searchGoodRecyclerAdapter.setStrings("品类", title, shBrands.get(tlTabs.getSelectedTabPosition()).getSh_name());
        }else {
            searchGoodRecyclerAdapter.notifyItemRangeInserted(goodList.size() - dataBean.getSh_items().getSh_products().size(), dataBean.getSh_items().getSh_products().size());
            searchGoodRecyclerAdapter.loadMoreComplete();
        }

//        searchGoodRecyclerAdapter.setNewData(goodList);

        if (goodList.size() >= total) {
            searchGoodRecyclerAdapter.setEnableLoadMore(false);
            searchGoodRecyclerAdapter.setFooterView(footView);

            footView.setVisibility(View.VISIBLE);
        } else {
            footView.setVisibility(View.GONE);
        }
        if (changeBrand) {
            //其它
            llConditionOther.setVisibility(View.VISIBLE);
            llConditionOther.removeAllViews();
            if (dataBean.getSh_items().getSh_attributes() != null) {
                cloneAttrBeans = (List<SearchGoodBean.DataBean.ShAttributesBean>) CloneUtil.deepClone(dataBean.getSh_items().getSh_attributes());
                for (SearchGoodBean.DataBean.ShAttributesBean bean : cloneAttrBeans) {
                    LinearLayout linearLayout = (LinearLayout) View.inflate(mContext, R.layout.view_search_condition_selector, null);
                    TextView tv_attr_name = (TextView) linearLayout.findViewById(R.id.tv_attr_name);
                    ImageView iv_arrow = (ImageView) linearLayout.findViewById(R.id.iv_arrow);

                    tv_attr_name.setText(bean.getSh_attribute_name());
                    NonScrollGridView gridView = (NonScrollGridView) linearLayout.findViewById(R.id.noScrollGrid);
                    CategoryGridAdapter gridAdapter = new CategoryGridAdapter(mContext);
                    gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            SearchGoodBean.DataBean.ShAttributesBean.ShOptionsBean shOptionsBean = bean.getSh_options().get(position);
                            if (shOptionsBean.isCheck()) {
                                shOptionsBean.setCheck(false);
                            } else {
                                shOptionsBean.setCheck(true);
                            }
                            gridAdapter.notifyDataSetChanged();
                        }
                    });

                    iv_arrow.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (bean.attrOpen){
                                iv_arrow.setImageResource(R.mipmap.search_down);
                            }else {
                                iv_arrow.setImageResource(R.mipmap.search_up);
                            }
                            bean.attrOpen = !bean.attrOpen;
                            gridAdapter.setAllShow(bean.attrOpen);
                        }
                    });
                    gridView.setAdapter(gridAdapter);
                    gridAdapter.setAttrList(bean.getSh_options());

                    if (bean.getSh_options() != null && bean.getSh_options().size() > 3) {
                        iv_arrow.setVisibility(View.VISIBLE);
                        gridAdapter.setAllShow(false);
                    } else {
                        iv_arrow.setVisibility(View.GONE);
                    }
                    llConditionOther.addView(linearLayout);
                }
            } else {
                llConditionOther.setVisibility(View.GONE);
            }

            //活动
//            if(dataBean.getSh_promotions() != null){
//                clonePromotions = (List<SearchGoodBean.DataBean.ShPromotionsBean>) CloneUtil.deepClone(dataBean.getSh_promotions());
//            }else {
            llActivity.setVisibility(View.GONE);
//            }
//            initPromotions();
        }
    }


    private void initPromotions() {
        if(clonePromotions != null&&clonePromotions.size()>0){
            promotionAdapter = new PromotionAdapter(mContext);
            noScrollPromotion.setAdapter(promotionAdapter);
            promotionAdapter.setList(clonePromotions,"");

            noScrollPromotion.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    conditionBean.setPromotion_type(clonePromotions.get(position).getSh_id());
                    promotionAdapter.setList(clonePromotions,conditionBean.getPromotion_type());
                }
            });

        }else {
            llActivity.setVisibility(View.GONE);
        }
    }

//    @Override
//    public void showBrandList(CategoryBrandBean.DataBean dataBean) {
//        cids = dataBean.getSh_categorys();
//        brands = dataBean;
//        position = 0;
//        initViews();
//    }

    @Override
    public void searchError() {
        if(swipeLayout!=null){
            swipeLayout.setRefreshing(false);
        }
        emptyView.setVisibility(View.VISIBLE);
    }

    private void searchNewCondition() {
//        page = 1;
        if (goodList != null) {
            goodList.clear();
            emptyView.setVisibility(View.GONE);
            searchGoodRecyclerAdapter.notifyDataSetChanged();
        }
        recyclerView.scrollToPosition(0);
        footView.setVisibility(View.GONE);
        setSelectTag();

//        Log.e("======", "List--4");
        changeBrand = false;
        getData("1");
    }


    private void initAttributes() {
        llConditionOther.removeAllViews();
        if (cloneAttrBeans != null) {
            for (SearchGoodBean.DataBean.ShAttributesBean bean : cloneAttrBeans) {
                LinearLayout linearLayout = (LinearLayout) View.inflate(mContext, R.layout.view_search_condition_selector, null);
                TextView tv_attr_name = (TextView) linearLayout.findViewById(R.id.tv_attr_name);
                ImageView iv_arrow = (ImageView) linearLayout.findViewById(R.id.iv_arrow);

                tv_attr_name.setText(bean.getSh_attribute_name());
                NonScrollGridView gridView = (NonScrollGridView) linearLayout.findViewById(R.id.noScrollGrid);
                CategoryGridAdapter gridAdapter = new CategoryGridAdapter(mContext);
                gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        SearchGoodBean.DataBean.ShAttributesBean.ShOptionsBean shOptionsBean = bean.getSh_options().get(position);
//                        mRequestFocus(view);
                        if (shOptionsBean.isCheck()) {
                            shOptionsBean.setCheck(false);
                        } else {
                            shOptionsBean.setCheck(true);
                        }
                        gridAdapter.notifyDataSetChanged();
                    }
                });
                if (bean.getSh_options() != null && bean.getSh_options().size() > 3) {
                    iv_arrow.setVisibility(View.VISIBLE);
                } else {
                    iv_arrow.setVisibility(View.GONE);
                }
                iv_arrow.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (bean.attrOpen){
                            iv_arrow.setImageResource(R.mipmap.search_down);
                        }else {
                            iv_arrow.setImageResource(R.mipmap.search_down);
                        }
                        bean.attrOpen = !bean.attrOpen;
                        gridAdapter.setAllShow(bean.attrOpen);
                    }
                });
                gridView.setAdapter(gridAdapter);
                gridAdapter.setAttrList(bean.getSh_options());
                if (bean.getSh_options() != null && bean.getSh_options().size() > 3) {
                    iv_arrow.setVisibility(View.VISIBLE);
                    gridAdapter.setAllShow(false);
                } else {
                    iv_arrow.setVisibility(View.GONE);
                }
                llConditionOther.addView(linearLayout);
            }
        } else {
            llConditionOther.setVisibility(View.GONE);
        }
    }

//    private void mRequestFocus(View view) {
//        view.setFocusable(true);
//        view.setFocusableInTouchMode(true);
//        view.requestFocus();
//    }

    @OnClick({R.id.rl_back, R.id.tv_reset, R.id.tv_complete, R.id.tv_default, R.id.tv_sale_volume, R.id.tv_price,R.id.tv_price_icon, R.id.tv_filt_layout})
    void onClick(View view) {
        switch (view.getId()) {
            case R.id.rl_back:
                finish();
                break;
            case R.id.tv_reset:
                resetAttr();
                break;
            case R.id.tv_complete:
                String minPrice = etMinPrice.getText().toString().trim();
                String maxPrice = etMaxPrice.getText().toString().trim();

                conditionBean.setStart_price(minPrice);
                conditionBean.setEnd_price(maxPrice);
                conditionBean.setAttributes(null);
                if (cloneAttrBeans != null) {
                    Map<String, String> map = new HashMap<>();
                    for (SearchGoodBean.DataBean.ShAttributesBean shAttributesBean: cloneAttrBeans) {
                        if (shAttributesBean.getSh_options() != null) {
                            for (SearchGoodBean.DataBean.ShAttributesBean.ShOptionsBean shOptionsBean : shAttributesBean.getSh_options()) {
                                if (shOptionsBean.isCheck()) {
                                    if (map.containsKey(shAttributesBean.getSh_attribute_id())) {
                                        String str = map.get(shAttributesBean.getSh_attribute_id());
                                        map.put(shAttributesBean.getSh_attribute_id(), str + "," + shOptionsBean.getSh_value());
                                    } else {
                                        map.put(shAttributesBean.getSh_attribute_id(), shOptionsBean.getSh_value());
                                    }
                                }
                            }
                        }
                    }
                    conditionBean.setAttributes(map);
                    category_brand_ids = new ArrayList<>();
                    for (CategoryDetailBean.ShItemsBean.ShCategorysBean category: category_brands) {
                        if (category.isCheck()) {
                            category_brand_ids.add("0".equals(type) ? category.getSh_id() : category.getSh_cid());
                        }
                    }
                }

                searchNewCondition();
                drawerLayout.closeDrawers();
                break;
            case R.id.tv_default:
                clickDefault();
                break;
            case R.id.tv_sale_volume:
                clickVolume();
                break;
            case R.id.tv_price_icon:
            case R.id.tv_price:
                clickPrice();
                break;
            case R.id.tv_filt_layout:
                drawerLayout.openDrawer(Gravity.RIGHT);
                break;
        }
    }

    private void resetAttr() {
        category_brand_ids = new ArrayList<>();
        if (cloneAttrBeans != null) {
            for (SearchGoodBean.DataBean.ShAttributesBean attributesBean: cloneAttrBeans) {
                if (attributesBean.getSh_options() != null) {
                    for (SearchGoodBean.DataBean.ShAttributesBean.ShOptionsBean shOptionsBean : attributesBean.getSh_options()) {
                        shOptionsBean.setCheck(false);
                    }
                }
            }
        }

        if (category_brands != null){
            for (CategoryDetailBean.ShItemsBean.ShCategorysBean bean: category_brands) {
                bean.setCheck(false);
            }
            categoryGridAdapter.notifyDataSetChanged();
        }


        initAttributes();
        etMinPrice.setText("");
        etMaxPrice.setText("");

        //初始化特惠和秒杀
//        tvDiscount.setBackgroundResource(R.drawable.bg_search_et);
//        tvDiscount.setTextColor(0xff444444);
//        tvFullCount.setBackgroundResource(R.drawable.bg_search_et);
//        tvFullCount.setTextColor(0xff444444);
        conditionBean.setPromotion_type("");
        if(promotionAdapter!=null){
            promotionAdapter.setList(clonePromotions,conditionBean.getPromotion_type());
        }
    }

    private void clickDefault() {
        if ("new".equals(sort)) return;

       if ("hot".equals(sort)) {
            tvDefault.setTextColor(getResources().getColor(R.color.text_red));
            tvSaleVolume.setTextColor(0xFF222222);
            holder.tvDefault.setTextColor(getResources().getColor(R.color.text_red));
            holder.tvSaleVolume.setTextColor(0xFF222222);
            sort = "new";
            searchNewCondition();
        } else if ("price_desc".equals(sort) || "price_asc".equals(sort)) {
            tvDefault.setTextColor(getResources().getColor(R.color.text_red));
            tvSaleVolume.setTextColor(0xFF222222);
            holder.tvDefault.setTextColor(getResources().getColor(R.color.text_red));
            holder.tvSaleVolume.setTextColor(0xFF222222);
            tvPriceIcon.setImageResource(R.mipmap.paixu_icon);
            holder.tvPriceIcon.setImageResource(R.mipmap.paixu_icon);
//            Drawable nav_up = getResources().getDrawable(R.mipmap.paixu_icon);
//            nav_up.setBounds(0, 0, nav_up.getMinimumWidth(), nav_up.getMinimumHeight());
//            tvPrice.setCompoundDrawables(null, null, nav_up, null);
//            holder.tvPrice.setCompoundDrawables(null, null, nav_up, null);
            tvPrice.setTextColor(0xFF222222);
            holder.tvPrice.setTextColor(0xFF222222);
            sort = "new";
            searchNewCondition();
        }
    }

    private void clickVolume() {
        if ("hot".equals(sort)) return;
        if ("new".equals(sort)) {
            tvSaleVolume.setTextColor(getResources().getColor(R.color.text_red));
            tvDefault.setTextColor(0xFF222222);
            holder.tvSaleVolume.setTextColor(getResources().getColor(R.color.text_red));
            holder.tvDefault.setTextColor(0xFF222222);
            sort = "hot";
            searchNewCondition();
        } else if ("price_desc".equals(sort) || "price_asc".equals(sort)) {
            tvPriceIcon.setImageResource(R.mipmap.paixu_icon);
            holder.tvPriceIcon.setImageResource(R.mipmap.paixu_icon);
//            Drawable nav_up = getResources().getDrawable(R.mipmap.paixu_icon);
//            nav_up.setBounds(0, 0, nav_up.getMinimumWidth(), nav_up.getMinimumHeight());
//            tvPrice.setCompoundDrawables(null, null, nav_up, null);
//            holder.tvPrice.setCompoundDrawables(null, null, nav_up, null);
            tvSaleVolume.setTextColor(getResources().getColor(R.color.text_red));
            holder.tvSaleVolume.setTextColor(getResources().getColor(R.color.text_red));
            tvPrice.setTextColor(0xFF222222);
            holder.tvPrice.setTextColor(0xFF222222);
            sort = "hot";
            searchNewCondition();
        }
    }

    private void clickPrice() {
        if ("new".equals(sort)) {
            sort = "price_desc";
            tvSaleVolume.setTextColor(0xFF222222);
            tvDefault.setTextColor(0xFF222222);
            holder.tvSaleVolume.setTextColor(0xFF222222);
            holder.tvDefault.setTextColor(0xFF222222);
            tvPriceIcon.setImageResource(R.mipmap.paixu_down_icon);
            holder.tvPriceIcon.setImageResource(R.mipmap.paixu_down_icon);
//            Drawable nav_up = getResources().getDrawable(R.mipmap.paixu_down_icon);
//            nav_up.setBounds(0, 0, nav_up.getMinimumWidth(), nav_up.getMinimumHeight());
//            tvPrice.setCompoundDrawables(null, null, nav_up, null);
            tvPrice.setTextColor(getResources().getColor(R.color.text_red));
            holder.tvPrice.setTextColor(getResources().getColor(R.color.text_red));
//            holder.tvPrice.setCompoundDrawables(null, null, nav_up, null);
        } else if ("hot".equals(sort)) {
            sort = "price_desc";
            tvSaleVolume.setTextColor(0xFF222222);
            tvDefault.setTextColor(0xFF222222);

            holder.tvSaleVolume.setTextColor(0xFF222222);
            holder.tvDefault.setTextColor(0xFF222222);
            tvPriceIcon.setImageResource(R.mipmap.paixu_down_icon);
            holder.tvPriceIcon.setImageResource(R.mipmap.paixu_down_icon);
//            Drawable nav_up = getResources().getDrawable(R.mipmap.paixu_down_icon);
//            nav_up.setBounds(0, 0, nav_up.getMinimumWidth(), nav_up.getMinimumHeight());
            tvPrice.setTextColor(getResources().getColor(R.color.text_red));
            holder.tvPrice.setTextColor(getResources().getColor(R.color.text_red));
//            tvPrice.setCompoundDrawables(null, null, nav_up, null);
//            holder.tvPrice.setCompoundDrawables(null, null, nav_up, null);
        } else if ("price_desc".equals(sort)) {
            sort = "price_asc";
            tvPriceIcon.setImageResource(R.mipmap.paixu_top_icon);
            holder.tvPriceIcon.setImageResource(R.mipmap.paixu_top_icon);
//            Drawable nav_up = getResources().getDrawable(R.mipmap.paixu_top_icon);
//            nav_up.setBounds(0, 0, nav_up.getMinimumWidth(), nav_up.getMinimumHeight());
//            tvPrice.setCompoundDrawables(null, null, nav_up, null);
//            holder.tvPrice.setCompoundDrawables(null, null, nav_up, null);
        } else if ("price_asc".equals(sort)) {
            sort = "price_desc";
            tvPriceIcon.setImageResource(R.mipmap.paixu_down_icon);
            holder.tvPriceIcon.setImageResource(R.mipmap.paixu_down_icon);
//            Drawable nav_up = getResources().getDrawable(R.mipmap.paixu_down_icon);
//            nav_up.setBounds(0, 0, nav_up.getMinimumWidth(), nav_up.getMinimumHeight());
//            tvPrice.setCompoundDrawables(null, null, nav_up, null);
//            holder.tvPrice.setCompoundDrawables(null, null, nav_up, null);
        }
        searchNewCondition();
    }

    public void  getData(String page){
        if(mPresenter == null || conditionBean == null) return;
        mPresenter.getBrandGoodList(changeBrand, conditionBean.getAttributes()==null?new HashMap<>():conditionBean.getAttributes(),cid,type,("0".equals(type))?brandcategoryId:"",("1".equals(type))?brandcategoryId:"",("0".equals(type))?category_brand_ids:new ArrayList<>(),
                ("1".equals(type))?category_brand_ids:new ArrayList<>(),conditionBean.getStart_price(), conditionBean.getEnd_price(), page,
                PAGE_SIZE, sort, conditionBean.getPromotion_type());
    }

    @Override
    protected void onPause() {
        hideSoftInput(etMaxPrice);
        super.onPause();
    }

    private void conditionType() {

        holder.tvDefault.setOnClickListener(v -> {
            clickDefault();
        });
        holder.tvSaleVolume.setOnClickListener(v -> {
            clickVolume();
        });
        holder.tvPrice.setOnClickListener(v -> {
            clickPrice();
        });
    }


    static class ViewHolder {
        @BindView(R.id.iv_banner)
        ImageView ivBanner;
        @BindView(R.id.tv_default)
        TextView tvDefault;
        @BindView(R.id.tv_sale_volume)
        TextView tvSaleVolume;
        @BindView(R.id.tv_price)
        TextView tvPrice;
        @BindView(R.id.tv_price_icon)
        ImageView tvPriceIcon;
        @BindView(R.id.tv_filt)
        TextView tvFilt;
        @BindView(R.id.tv_filt_layout)
        LinearLayout tvFiltLayout;
        @BindView(R.id.ll_selector)
        LinearLayout llSelector;

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }
}
